package com.javase.多线程.自旋锁;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Auther: liyanhao
 * @Description: 自旋锁
 * @Date: 2022/5/15 10:12
 * @Version: v1.0
 */
public class SpinLockMainTest {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        System.out.println(Thread.currentThread().getName() + "/t" + "come in");
        while (!atomicReference.compareAndSet(null, Thread.currentThread())) {
            System.out.println(Thread.currentThread().getName()+"正在自旋获取锁....");
        }
        System.out.println(Thread.currentThread().getName()+"获取锁成功，执行业务操作");
    }

    public void myUnlock() {
        atomicReference.compareAndSet(Thread.currentThread(), null);
        System.out.println(Thread.currentThread().getName()+"释放自旋锁");
    }

    public static void main(String[] args) {
        //测试自旋锁
        SpinLockMainTest spinLockMainTest = new SpinLockMainTest();
        new Thread(() -> {
            try {
                spinLockMainTest.myLock();
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                spinLockMainTest.myUnlock();
            }
        }, "线程A").start();
        new Thread(()->{
            spinLockMainTest.myLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                spinLockMainTest.myUnlock();
            }
        },"线程B").start();
    }
}

/**
 * package com.juc.juc高级.自旋锁;
 * <p>
 * import java.util.concurrent.TimeUnit;
 * import java.util.concurrent.atomic.AtomicReference;
 * <p>
 * public class SpinLockDemo {
 * AtomicReference<Thread> atomicReference = new AtomicReference<>();
 * <p>
 * public void myLock(){
 * System.out.println(Thread.currentThread().getName()+"\t"+" come in");
 * while (!atomicReference.compareAndSet(null,Thread.currentThread())){
 * System.out.print("..");
 * }
 * System.out.println(Thread.currentThread().getName()+"\t"+" 持有锁成功");
 * }
 * public void myUnlock(){
 * atomicReference.compareAndSet(Thread.currentThread(),null);
 * System.out.println(Thread.currentThread().getName()+"\t"+" 释放锁成功");
 * }
 * <p>
 * public static void main(String[] args) {
 * SpinLockDemo spinLockDemo = new SpinLockDemo();
 * new Thread(()->{
 * spinLockDemo.myLock();
 * try {
 * TimeUnit.SECONDS.sleep(3);
 * } catch (InterruptedException e) {
 * e.printStackTrace();
 * }
 * spinLockDemo.myUnlock();
 * },"t1").start();
 * <p>
 * new Thread(()->{
 * spinLockDemo.myLock();
 * try {
 * TimeUnit.SECONDS.sleep(3);
 * } catch (InterruptedException e) {
 * e.printStackTrace();
 * }
 * spinLockDemo.myUnlock();
 * },"t2").start();
 * <p>
 * }
 * <p>
 * <p>
 * <p>
 * }
 */